<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图书管理系统</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- 配置Tailwind自定义颜色和字体 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#36CFC9',
                        neutral: '#F5F7FA',
                        'neutral-dark': '#4E5969'
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .transition-all-300 {
                transition: all 300ms ease-in-out;
            }
        }
    </style>
</head>

<body class="bg-neutral font-inter text-gray-800 min-h-screen">
    <!-- 顶部导航栏 -->
    <nav class="bg-white shadow-md sticky top-0 z-50 transition-all duration-300">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between h-16 items-center">
                <div class="flex items-center space-x-6">
                    <h1 class="text-xl font-bold text-primary flex items-center">
                        <i class="fa fa-book mr-2"></i>图书管理系统
                    </h1>
                    <div class="relative hidden md:block">
                        <input type="text" id="searchInput" placeholder="搜索书名或作者..."
                            class="w-72 pl-10 pr-4 py-2 rounded-lg border border-gray-300 focus:ring-2 focus:ring-primary/50 focus:border-primary focus:outline-none transition-all-300">
                        <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                            <i class="fa fa-search text-gray-400"></i>
                        </div>
                    </div>
                </div>
                <div class="flex items-center space-x-4">
                    <button onclick="exportBooks()"
                        class="text-gray-600 hover:text-primary transition-all-300 px-3 py-2 rounded-lg hover:bg-gray-100 flex items-center">
                        <i class="fa fa-download mr-2"></i>导出
                    </button>
                    <button id="addBookBtn"
                        class="bg-primary text-white px-4 py-2 rounded-lg hover:bg-primary/90 transition-all-300 shadow-sm hover:shadow flex items-center">
                        <i class="fa fa-plus mr-2"></i>添加图书
                    </button>
                </div>
            </div>
            <!-- 移动端搜索框 -->
            <div class="md:hidden pb-4">
                <div class="relative">
                    <input type="text" id="mobileSearchInput" placeholder="搜索书名或作者..."
                        class="w-full pl-10 pr-4 py-2 rounded-lg border border-gray-300 focus:ring-2 focus:ring-primary/50 focus:border-primary focus:outline-none">
                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                        <i class="fa fa-search text-gray-400"></i>
                    </div>
                </div>
            </div>
        </div>
    </nav>

    <!-- 主要内容区域 -->
    <main class="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
        <!-- 统计卡片 -->
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-6">
            <div class="bg-white rounded-xl shadow-sm p-6 border border-gray-100 hover:shadow-md transition-all-300">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-neutral-dark text-sm">总藏书量</p>
                        <h3 class="text-3xl font-bold mt-1" id="totalBooks">0</h3>
                    </div>
                    <div class="w-12 h-12 rounded-full bg-primary/10 flex items-center justify-center text-primary">
                        <i class="fa fa-book text-xl"></i>
                    </div>
                </div>
            </div>
            <div class="bg-white rounded-xl shadow-sm p-6 border border-gray-100 hover:shadow-md transition-all-300">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-neutral-dark text-sm">可借图书</p>
                        <h3 class="text-3xl font-bold mt-1" id="availableBooks">0</h3>
                    </div>
                    <div class="w-12 h-12 rounded-full bg-green-100 flex items-center justify-center text-green-600">
                        <i class="fa fa-check-circle text-xl"></i>
                    </div>
                </div>
            </div>
            <div class="bg-white rounded-xl shadow-sm p-6 border border-gray-100 hover:shadow-md transition-all-300">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-neutral-dark text-sm">已借出</p>
                        <h3 class="text-3xl font-bold mt-1" id="borrowedBooks">0</h3>
                    </div>
                    <div class="w-12 h-12 rounded-full bg-yellow-100 flex items-center justify-center text-yellow-600">
                        <i class="fa fa-clock-o text-xl"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- 图书列表 -->
        <div class="bg-white shadow-sm rounded-xl border border-gray-100 overflow-hidden">
            <div class="px-4 py-5 sm:p-6">
                <div class="flex justify-between items-center mb-6">
                    <h2 class="text-lg font-semibold">图书列表</h2>
                    <div class="text-sm text-gray-500" id="booksCount">显示 0 本图书</div>
                </div>
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                            <tr>
                                <th
                                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                    书名</th>
                                <th
                                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                    作者</th>
                                <th
                                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                    状态</th>
                                <th
                                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                    操作</th>
                            </tr>
                        </thead>
                        <tbody id="booksList" class="bg-white divide-y divide-gray-200">
                            <!-- 图书列表将通过 JavaScript 动态添加 -->
                            <tr class="text-center">
                                <td colspan="4" class="px-6 py-10 text-gray-500">
                                    <div class="flex flex-col items-center">
                                        <i class="fa fa-search text-3xl mb-2 text-gray-300"></i>
                                        <p>暂无图书数据</p>
                                    </div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </main>

    <!-- 添加/编辑图书模态框 -->
    <div id="bookModal"
        class="fixed inset-0 bg-gray-500 bg-opacity-75 hidden flex items-center justify-center z-50 transition-opacity duration-300">
        <div class="bg-white rounded-xl w-full max-w-md mx-4 transform transition-all duration-300 scale-95 opacity-0"
            id="modalContent">
            <div class="px-4 py-5 sm:p-6">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="text-lg font-medium text-gray-900" id="modalTitle">添加新图书</h3>
                    <button onclick="closeModal()" class="text-gray-400 hover:text-gray-500">
                        <i class="fa fa-times"></i>
                    </button>
                </div>
                <form id="bookForm">
                    <input type="hidden" id="bookId">
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">书名 <span
                                    class="text-red-500">*</span></label>
                            <input type="text" name="title" id="title" required
                                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring focus:ring-primary focus:ring-opacity-50 transition-all-300">
                            <p class="mt-1 text-red-500 text-xs hidden" id="titleError">请输入书名</p>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">作者 <span
                                    class="text-red-500">*</span></label>
                            <input type="text" name="author" id="author" required
                                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring focus:ring-primary focus:ring-opacity-50 transition-all-300">
                            <p class="mt-1 text-red-500 text-xs hidden" id="authorError">请输入作者</p>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">描述</label>
                            <textarea name="description" id="description"
                                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring focus:ring-primary focus:ring-opacity-50 transition-all-300"
                                rows="3" placeholder="简要描述图书内容..."></textarea>
                        </div>
                    </div>
                    <div class="mt-6 space-y-3 sm:space-y-0 sm:flex sm:space-x-3">
                        <button type="submit"
                            class="inline-flex justify-center w-full sm:w-auto rounded-md border border-transparent shadow-sm px-4 py-2 bg-primary text-base font-medium text-white hover:bg-primary/90 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary sm:text-sm transition-all-300">
                            保存
                        </button>
                        <button type="button" onclick="closeModal()"
                            class="mt-3 w-full sm:w-auto inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary sm:text-sm transition-all-300">
                            取消
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- 通知提示 -->
    <div id="notification"
        class="fixed bottom-5 right-5 bg-white shadow-lg rounded-lg p-4 transform translate-y-20 opacity-0 transition-all duration-300 flex items-center max-w-sm z-50">
        <div id="notificationIcon" class="mr-3 text-green-500">
            <i class="fa fa-check-circle text-xl"></i>
        </div>
        <div>
            <h4 class="font-medium" id="notificationTitle">操作成功</h4>
            <p class="text-sm text-gray-600" id="notificationMessage">图书已添加</p>
        </div>
        <button onclick="hideNotification()" class="ml-4 text-gray-400 hover:text-gray-500">
            <i class="fa fa-times"></i>
        </button>
    </div>

    <script>
        // 全局变量
        let currentEditId = null;

        // 获取DOM元素
        const booksList = document.getElementById('booksList');
        const bookModal = document.getElementById('bookModal');
        const modalContent = document.getElementById('modalContent');
        const bookForm = document.getElementById('bookForm');
        const addBookBtn = document.getElementById('addBookBtn');
        const modalTitle = document.getElementById('modalTitle');
        const bookIdInput = document.getElementById('bookId');
        const titleInput = document.getElementById('title');
        const authorInput = document.getElementById('author');
        const descriptionInput = document.getElementById('description');
        const titleError = document.getElementById('titleError');
        const authorError = document.getElementById('authorError');
        const totalBooksEl = document.getElementById('totalBooks');
        const availableBooksEl = document.getElementById('availableBooks');
        const borrowedBooksEl = document.getElementById('borrowedBooks');
        const booksCountEl = document.getElementById('booksCount');
        const notification = document.getElementById('notification');
        const notificationTitle = document.getElementById('notificationTitle');
        const notificationMessage = document.getElementById('notificationMessage');
        const notificationIcon = document.getElementById('notificationIcon');

        // 加载图书列表
        async function loadBooks() {
            try {
                const response = await fetch('/api/books');
                const books = await response.json();

                // 更新统计数据
                updateStatistics(books);

                // 渲染图书列表
                renderBooks(books);
            } catch (error) {
                console.error('加载图书列表失败:', error);
                showNotification('加载失败', '无法获取图书数据，请稍后重试', 'error');
            }
        }

        // 更新统计数据
        function updateStatistics(books) {
            const total = books.length;
            const available = books.filter(book => book.status === 'available').length;
            const borrowed = total - available;

            totalBooksEl.textContent = total;
            availableBooksEl.textContent = available;
            borrowedBooksEl.textContent = borrowed;
            booksCountEl.textContent = `显示 ${total} 本图书`;
        }

        // 渲染图书列表
        function renderBooks(books) {
            if (books.length === 0) {
                booksList.innerHTML = `
                    <tr class="text-center">
                        <td colspan="4" class="px-6 py-10 text-gray-500">
                            <div class="flex flex-col items-center">
                                <i class="fa fa-book text-3xl mb-2 text-gray-300"></i>
                                <p>没有找到图书</p>
                            </div>
                        </td>
                    </tr>
                `;
                return;
            }

            booksList.innerHTML = books.map(book => `
                <tr class="hover:bg-gray-50 transition-all-300">
                    <td class="px-6 py-4 whitespace-nowrap">
                        <div class="font-medium text-gray-900">${book.title}</div>
                        ${book.description ? `<div class="text-sm text-gray-500 mt-1 line-clamp-2">${book.description}</div>` : ''}
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap">${book.author}</td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full 
                            ${book.status === 'available' ? 'bg-green-100 text-green-800' : 'bg-yellow-100 text-yellow-800'}">
                            ${book.status === 'available' ? '可借' : '已借出'}
                        </span>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium space-x-2">
                        <button onclick="${book.status === 'available' ? 'borrowBook' : 'returnBook'}(${book.id})" 
                            class="text-blue-600 hover:text-blue-900 transition-all-300">
                            <i class="fa fa-${book.status === 'available' ? 'book' : 'undo'} mr-1"></i>
                        ${book.status === 'available' ? '借阅' : '归还'}
                        </button>
                        <button onclick="editBook(${book.id})" class="text-primary hover:text-primary/80 transition-all-300">
                            <i class="fa fa-edit mr-1"></i>编辑
                        </button>
                        <button onclick="deleteBook(${book.id})" class="text-red-600 hover:text-red-900 transition-all-300">
                            <i class="fa fa-trash mr-1"></i>删除
                        </button>
                    </td>
                </tr>
            `).join('');
        }

        // 打开模态框
        function openModal(id=null) {

            bookModal.classList.remove('hidden');
            bookModal.classList.add('flex');

            // 动画效果
            setTimeout(() => {
                modalContent.classList.remove('scale-95', 'opacity-0');
                modalContent.classList.add('scale-100', 'opacity-100');
            }, 10);
            
            

            if (id) {
                // 编辑模式
                currentEditId = id;
                modalTitle.textContent = '编辑图书';
                bookIdInput.value = id;
            } else {
                // 添加新图书
                bookForm.reset();
                currentEditId = null;
                modalTitle.textContent = '添加新图书';
                bookIdInput.value = '';
            }

            // 隐藏错误提示
            titleError.classList.add('hidden');
            authorError.classList.add('hidden');
        }

        // 关闭模态框
        function closeModal() {
            modalContent.classList.remove('scale-100', 'opacity-100');
            modalContent.classList.add('scale-95', 'opacity-0');

            setTimeout(() => {
                bookModal.classList.remove('flex');
                bookModal.classList.add('hidden');
            }, 300);
        }

        // 添加图书按钮点击事件
        addBookBtn.addEventListener('click',()=>openModal());

        // 点击模态框外部关闭
        bookModal.addEventListener('click', (e) => {
            if (e.target === bookModal) {
                closeModal();
            }
        });

        // 按ESC键关闭模态框
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape' && !bookModal.classList.contains('hidden')) {
                closeModal();
            }
        });

        // 表单提交处理
        bookForm.addEventListener('submit', async (e) => {
            e.preventDefault();

            const bookId = document.getElementById('bookId').value;
            const formData = {
                title: document.getElementById('title').value.trim(),
                author: document.getElementById('author').value.trim(),
                description: document.getElementById('description').value.trim()
            };

            try {
                console.log("id",bookId)
                const url = bookId ? `/api/books/${bookId}` : '/api/books';
                const method = bookId ? 'PUT' : 'POST';

                const response = await fetch(url, {
                    method: method,
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(formData)
                });
                console.log("返回体",response)
                if (!response.ok) {
                    throw new Error('操作失败');
                }

                closeModal();
                loadBooks();
                showNotification(
                    bookId ? '编辑成功' : '添加成功',
                    bookId ? '图书信息已更新' : '新图书已添加',
                    'success'
                );
            } catch (error) {
                console.error('操作失败:', error);
                showNotification('操作失败', '请重试', 'error');
            }
        });

        // 删除图书
        async function deleteBook(id) {
            if (!confirm('确定要删除这本图书吗？此操作不可恢复。')) return;

            try {
                const response = await fetch(`/api/books/${id}`, {
                    method: 'DELETE'
                });

                if (response.ok) {
                    loadBooks();
                    showNotification('删除成功', '图书已从系统中移除', 'success');
                } else {
                    const error = await response.json();
                    showNotification('删除失败', error.message, 'error');
                }
            } catch (error) {
                console.error('删除图书失败:', error);
                showNotification('删除失败', '网络错误，请重试', 'error');
            }
        }

        // 编辑图书函数
        async function editBook(id) {
            console.log(`编辑图书 ID: ${id}`);
            currentEditId = id;
            try {
                const response = await fetch(`/api/books/${id}`);
                if (!response.ok) {
                    throw new Error('获取图书信息失败');
                }

                const book = await response.json();
                console.log('获取到的图书信息:', book);
                // 填充表单
                document.getElementById('bookId').value = book.id;
                document.getElementById('title').value = book.title;
                document.getElementById('author').value = book.author;
                document.getElementById('description').value = book.description || '';

                // 更新模态框标题
                document.getElementById('modalTitle').textContent = '编辑图书';

                // 打开模态框
                openModal(id);

            } catch (error) {
                console.error('编辑失败:', error);
                showNotification('编辑失败', '无法获取图书信息', 'error');
            }
        }

        // 搜索功能
        function setupSearch() {
            const searchInput = document.getElementById('searchInput');
            const mobileSearchInput = document.getElementById('mobileSearchInput');

            const handleSearch = debounce(async (value) => {
                try {
                    if (!value.trim()) {
                        // 如果搜索框为空，重新加载所有图书
                        loadBooks();
                        return;
                    }
                    const response = await fetch(`/api/books/search?q=${encodeURIComponent(value)}`);
                    console.log("返回体",response)
                    if (!response.ok) {
                        throw new Error('搜索失败');
                    }
                    const books = await response.json();
                    renderBooks(books);
                } catch (error) {
                    console.error('搜索失败:', error);
                    showNotification('搜索失败', '请重试', 'error');
                }
            }, 300);

            // 为两个搜索框添加事件监听
            [searchInput, mobileSearchInput].forEach(input => {
                if (input) {
                    input.addEventListener('input', (e) => handleSearch(e.target.value));
                }
            });
        }

        // 确保在页面加载时初始化搜索功能
        document.addEventListener('DOMContentLoaded', () => {
            setupSearch();
            loadBooks();
        });

        // 借阅功能
        async function borrowBook(id) {
            try {
                const response = await fetch(`/api/books/${id}/borrow`, {
                    method: 'PUT'
                });

                if (response.ok) {
                    loadBooks();
                    showNotification('借阅成功', '图书已成功借出', 'success');
                } else {
                    const error = await response.json();
                    showNotification('借阅失败', error.message, 'error');
                }
            } catch (error) {
                console.error('借阅失败:', error);
                showNotification('借阅失败', '网络错误，请重试', 'error');
            }
        }

        async function returnBook(id) {
            try {
                const response = await fetch(`/api/books/${id}/return`, {
                    method: 'PUT'
                });

                if (response.ok) {
                    loadBooks();
                    showNotification('归还成功', '图书已归还', 'success');
                } else {
                    const error = await response.json();
                    showNotification('归还失败', error.message, 'error');
                }
            } catch (error) {
                console.error('归还失败:', error);
                showNotification('归还失败', '网络错误，请重试', 'error');
            }
        }

        // 导出功能
        async function exportBooks() {
            try {
                const response = await fetch('/api/books/export');
                const blob = await response.blob();
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = '图书列表.xlsx';
                document.body.appendChild(a);
                a.click();

                // 清理
                setTimeout(() => {
                    window.URL.revokeObjectURL(url);
                    document.body.removeChild(a);
                }, 100);

                showNotification('导出成功', '图书列表已导出为Excel文件', 'success');
            } catch (error) {
                console.error('导出失败:', error);
                showNotification('导出失败', '无法导出图书列表', 'error');
            }
        }

        // 显示通知
        function showNotification(title, message, type = 'success') {
            notificationTitle.textContent = title;
            notificationMessage.textContent = message;

            // 设置图标和颜色
            if (type === 'success') {
                notificationIcon.className = 'mr-3 text-green-500';
                notificationIcon.innerHTML = '<i class="fa fa-check-circle text-xl"></i>';
            } else if (type === 'error') {
                notificationIcon.className = 'mr-3 text-red-500';
                notificationIcon.innerHTML = '<i class="fa fa-exclamation-circle text-xl"></i>';
            }

            // 显示通知
            notification.classList.remove('translate-y-20', 'opacity-0');
            notification.classList.add('translate-y-0', 'opacity-100');

            // 3秒后自动隐藏
            setTimeout(hideNotification, 3000);
        }

        // 隐藏通知
        function hideNotification() {
            notification.classList.remove('translate-y-0', 'opacity-100');
            notification.classList.add('translate-y-20', 'opacity-0');
        }

        // 防抖函数
        function debounce(func, wait) {
            let timeout;
            return function executedFunction(...args) {
                const later = () => {
                    clearTimeout(timeout);
                    func(...args);
                };
                clearTimeout(timeout);
                timeout = setTimeout(later, wait);
            };
        }

        // 初始化
        function init() {
            loadBooks();
            setupSearch();
        }

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', init);
    </script>
</body>

</html>